<template>
  <div class="api-call-page">
    <el-card>
      <el-select v-model="selectValue" :disabled="loading" clearable placeholder="请选择 API" style="width: 300px;">
        <RecycleScroller
            v-if="processedData.length > 0"
            :items="processedData"
            :item-size="50"
            key-field="value"
        >
          <template #default="{ item }">
            <el-option
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </template>
        </RecycleScroller>
      </el-select>
      <el-form label-width="120px" style="margin-top: 10px;">
        <el-form-item label="动态参数 (JSON 格式)">
          <el-input
              v-model="dynamicParamsInput"
              type="textarea"
              :rows="3"
              placeholder='例如: {"key1": "value1", "key2": "value2"}'
          />
        </el-form-item>
        <el-form-item label="动态请求头 (JSON 格式)">
          <el-input
              v-model="dynamicHeadersInput"
              type="textarea"
              :rows="3"
              placeholder='例如: {"header1": "value1", "header2": "value2"}'
          />
        </el-form-item>
        <el-form-item label="动态请求体 (JSON 格式)">
          <el-input
              v-model="dynamicBodyInput"
              type="textarea"
              :rows="3"
              placeholder='例如: {"field1": "value1", "field2": "value2"}'
          />
        </el-form-item>
      </el-form>
      <el-button :loading="loading" :disabled="loading" type="primary" @click="callApi" style="margin-left: 10px;">
        执行 API
      </el-button>
      <el-button @click="clearAll">清空</el-button>
    </el-card>
    <el-card v-if="response" style="margin-top: 20px;">
      <h2>响应结果</h2>
      <p v-if="response.statusCode">状态码: {{ response.statusCode }}</p>
      <p v-if="response.errorMessage">错误信息: {{ response.errorMessage }}</p>
      <json-viewer
          :value="response"
          :expand-depth="1"
          boxed
          sort
          :show-array-index="false"
          copyable
      >
      </json-viewer>
    </el-card>
  </div>
</template>

<script>
import { RecycleScroller } from 'vue-virtual-scroller';
import 'vue-virtual-scroller/dist/vue-virtual-scroller.css';
import JsonViewer from 'vue-json-viewer'
import { callApi,getAllApiList } from "@/services/apiService";
export default {
  components: {
    // VueJsonTree,
    RecycleScroller,
    JsonViewer,
  },
  data() {
    return {
      processedData: [],
      selectValue: '',
      response: null,
      loading: false,
      timeout: 10000,
      timeoutId: null,
      dynamicParamsInput: '',
      dynamicHeadersInput: '',
      dynamicBodyInput: '',
    };
  },
  mounted() {
    this.getAllApiList();
  },
  methods: {
    async callApi() {
      if (this.loading) return;
      this.loading = true;
      this.timeoutId = setTimeout(() => {
        this.loading = false;
        this.$message.error('请求超时，请重试');
      }, this.timeout);

      let dynamicParams = {};
      let dynamicHeaders = {};
      let dynamicBody = null;

      try {
        if (this.dynamicParamsInput) {
          dynamicParams = JSON.parse(this.dynamicParamsInput);
        }
        if (this.dynamicHeadersInput) {
          dynamicHeaders = JSON.parse(this.dynamicHeadersInput);
        }
        if (this.dynamicBodyInput) {
          dynamicBody = JSON.parse(this.dynamicBodyInput);
        }
      } catch (error) {
        this.loading = false;
        this.$message.error('输入的参数格式不是有效的 JSON 格式，请检查');
        return;
      }

      try {
        const response = await callApi(
            this.selectValue,
            dynamicParams,
            dynamicHeaders,
            dynamicBody
        );
        this.response = response;
      } catch (error) {
        console.error('请求出错:', error);
        this.$message.error(error.message);
      } finally {
        clearTimeout(this.timeoutId);
        this.loading = false;
      }
    },
    async getAllApiList() {
      try {
        const response = await getAllApiList(true);
        if (response.data.success) {
          this.processedData = response.data.data.map((item) => ({
            value: item.id,
            label: item.name,
          }));
          console.log(this.processedData)
        } else {
          this.$message.error(response.data.message || '获取 API 列表失败');
        }
      } catch (error) {
        console.error('请求出错:', error);
        this.$message.error('获取 API 列表失败，请检查网络或 API 地址');
      }
    },
    clearAll() {
      this.selectValue = '';
      this.response = null;
      this.dynamicParamsInput = '';
      this.dynamicHeadersInput = '';
      this.dynamicBodyInput = '';
    },
  },
};
</script>

<style>
.api-call-page {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>